package cn.chenc.framework.security.jwt;


import cn.chenc.framework.core.component.AbstractJwtTemplate;
import cn.chenc.framework.core.consts.CommonConst;
import cn.chenc.framework.core.model.AbstractLoginUser;
import cn.chenc.framework.core.model.request.RequestHolder;
import cn.chenc.framework.core.util.StringUtils;
import cn.chenc.framework.core.util.ip.IpUtils;
import cn.chenc.framework.core.util.uuid.IdUtils;
import cn.chenc.framework.security.model.SecurityLoginUser;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt token验证处理
 *
 */
@Deprecated
public class SecurityJwtTemplate implements AbstractJwtTemplate {
    // 令牌自定义标识
    private String header= CommonConst.HEADER;

    // 令牌秘钥
    private String secret="abcdefghijklmnopqrstuvwxyz";

    // 令牌有效期（默认30分钟）
    private int expireTime=30;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public int getExpireTime() {
        return expireTime;
    }

    public void setExpireTime(int expireTime) {
        this.expireTime = expireTime;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    @Override
    public AbstractLoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(CommonConst.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            SecurityLoginUser user = (SecurityLoginUser) RequestHolder.getSession(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    @Override
    public void setLoginUser(AbstractLoginUser securityLoginUser)
    {
        if (StringUtils.isNotNull(securityLoginUser) && StringUtils.isNotEmpty(securityLoginUser.getToken()))
        {
            refreshToken(securityLoginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    @Override
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            RequestHolder.removeSession(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param securityLoginUser 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(AbstractLoginUser securityLoginUser)
    {
        String token = IdUtils.fastUUID();
        securityLoginUser.setToken(token);
        setUserAgent(securityLoginUser);
        refreshToken(securityLoginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(CommonConst.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param securityLoginUser
     * @return 令牌
     */
    @Override
    public void verifyToken(AbstractLoginUser securityLoginUser)
    {
        long expireTime = securityLoginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(securityLoginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param securityLoginUser 登录信息
     */
    @Override
    public void refreshToken(AbstractLoginUser securityLoginUser) {
        securityLoginUser.setLoginTime(System.currentTimeMillis());
        securityLoginUser.setExpireTime(securityLoginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(securityLoginUser.getToken());
        RequestHolder.setSession(userKey, securityLoginUser);
    }

    /**
     * 设置用户代理信息
     *
     * @param securityLoginUser 登录信息
     */
    @Override
    public void setUserAgent(AbstractLoginUser securityLoginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(RequestHolder.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(RequestHolder.getRequest());
        securityLoginUser.setIpaddr(ip);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CommonConst.TOKEN_PREFIX))
        {
            token = token.replace(CommonConst.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return CommonConst.LOGIN_TOKEN_KEY + uuid;
    }
}
